import md5 from 'js-md5'
import request from '@/utils/open/request'
import constant from '@/constant'
import common from '@/utils/open/common'
import vuxTool from '@/utils/open/vux-plugin'
import validate from '@/utils/open/validate'
import store from '@/store'
import { Encrypt, Decrypt } from '@/utils/open/secret'

/**
 * 系统请求工具类，
 * 注意：API接口只做请求数据和格式化数据的事情，其他事务一概不处理
 */
export default {
  /**
   * 接口例子模板
   *
   * @param param
   * @param resolve
   * @param reject
   */
  demo(param, resolve, reject) {
    const url = common.static.ctx + '///'
    request.get(url, param).then(res => {
      if (res) {
        if (res.code === 0) {
          resolve(res)
        } else {
          reject(res)
        }
      } else {
        reject(res)
      }
    }).catch(error => {
      reject(error)
    })
  },
  /**
   * 新修改密码
   *
   * @param param
   * @param resolve
   * @param reject
   */
  changePwd(param, resolve, reject) {
    const url = common.static.ctx + 'auth/api/v2/app/user/changepwd'
    request.putForm(url, param).then(res => {
      if (res) {
        if (res.code === 0) {
          resolve(res)
        } else {
          reject(res)
        }
      } else {
        reject(res)
      }
    }).catch(error => {
      reject(error)
    })
  },
  /**
   * 获取临时token
   * @param params
   */
  getToken(params) {
    return new Promise((resolve, reject) => {
      const url = constant.ctx + 'auth/api/v2/app/login/temporary'
      request.postForm(url, params).then((res) => {
        if (res.code === 0) {
          resolve(res)
        } else {
          resolve(res)
        }
      }).catch(e => {
        reject(e)
      })
    })
  },
  /**
   * 每27分钟刷新token
   */
  timingChangeToken(params) {
    return new Promise((resolve, reject) => {
      // const url = constant.ctx + '/auth/api/v2/app/sysuser/token/refresh'
      const url = constant.ctx + 'auth/api/v1/app/change/token'
      request.postForm(url, params).then((res) => {
        if (res.code === 0) {
          resolve(res)
        }
      }).catch(e => {
        reject(e)
      })
    })
  },
  /**
   * 登陆  18520583470 / lzd@2019
   * @param {String} name 账号
   * @param {String} pwd 密码
   * @param {String} loginType 登陆方式 1.手动登陆； 2.自动登陆（默认）
   * 注意：自动登陆成功，返回true； 若不成功，则提示相应问题，并返回false，自动切换为游客模式；
   * 手动登陆成功后，返回true
   */
  // login(name='18520583470', pwd='123456', loginType){
  login(params) {
    return new Promise((resolve, reject) => {
      // debugger
      const url = constant.ctx + 'auth/api/v2/app/login/check'
      request.postForm(url, params).then((res) => {
        // debugger
        if (res.code === 0) {
          resolve(res)
        } else {
          reject()
        }
      }).catch(e => {
        // debugger
        reject(e)
      })
    })
  },
  /**
   * 获取单位数据
   * 是否为默认单位描述（ 1436  是， 1437  否）
   */
  getUnitList() {
    vuxTool.loading('获取园所中')
    return new Promise((resolve, reject) => {
      // debugger
      const url = constant.ctx + 'auth/api/v2/app/sysuserunit/query/list'
      request.get(url, {}).then(res => {
        resolve(res)
      }).catch(res => {
        reject(res)
      })
    })
  },
  /**
   * 切换单位
   * @param [String] id 单位主键id
   * @return token
   */
  changeUnit(params) {
    return new Promise((resolve, reject) => {
      // debugger
      const url = constant.ctx + 'auth/api/v2/app/syscenterunit/change'
      request.putForm(url, params).then((res) => {
        // debugger
        if (res.code === 0) {
          resolve(res)
        }
      }).catch(e => {
        // debugger
        reject(e)
      })
    })
  },

  /**
   * 设置默认单位: 多个单位情况下，用户可以设置其中一个为默认单位
   * @param [String] id 单位主键id
   */
  setDefaultUnit(id) {
    return new Promise((resolve, reject) => {
      // debugger
      const params = {
        id: id // 单位主键id
      }
      const url = constant.ctx + 'auth/api/v2/app/syscenterunit/setdefault'
      request.putForm(url, params).then((res) => {
        // debugger
        if (res.code === 0) {
          resolve(res)
        }
      }).catch(e => {
        // debugger
        reject(e)
      })
    })
  },

  /**
   * 获取用户档案信息
   */
  getUserInfo() {
    vuxTool.loading('获取档案中')
    return new Promise((resolve, reject) => {
      const url = constant.ctx + 'auth/api/v2/app/sysuser/info'
      request.get(url, {}).then((res) => {
        if (res.code === 0) {
          resolve(res.result)
        }
      }).catch(e => {
        // debugger
        reject(e)
      })
    })
  },

  /**
   * 获取用户拥有的资源菜单
   */
  getPermission(data) {
    // console.log('getPermission', data)
    return new Promise((resolve, reject) => {
      const url = constant.ctx + 'auth/api/v2/app/syspermission/query/info'
      // debugger
      request.get(url, { type: data.identityType }).then((res) => {
        // console.log('获取用户拥有的资源菜单', res)
        if (res.code === 0) {
          resolve(res.result)
        } else {
          reject()
        }
      })
    })
  },
  /**
   * 注册
   * @param {String} phone 手机号
   * @param {String} code 随机编码
   * @param {String} captcha 验证码
   */
  register(phone, code, captcha) {
    const params = {
      phone: phone,
      code: code,
      captcha: captcha
    }
    const url = constant.ctx + 'auth/api/v2/app/user/register'
    request.postForm(url, params).then((res) => {
      // console.log('注册', res)
      // eslint-disable-next-line
      if (res.code === 0) {

      }
    })
  },

  /**
   * 更换手机号
   * @param {String} phone 要更换的手机号
   */
  changePhone(phone) {
    const params = {
      phone: phone
    }
    const url = constant.ctx + 'auth/api/v2/app/user/changephone'
    request.putForm(url, params).then((res) => {
      // console.log('更换手机号', res)
      // eslint-disable-next-line
      if (res.code === 0) {

      }
    })
  },

  /**
   * 修改密码
   * @param {String} oldPwd 旧密码（经过Md5处理过的）
   * @param {String} pwd 新密码（经过Md5处理过的）
   */
  changePWD(oldPwd, pwd) {
    const params = {
      oldPwd: md5(oldPwd),
      pwd: md5(pwd)
    }
    const url = constant.ctx + 'auth/api/v2/app/user/changepwd'
    request.putForm(url, params).then((res) => {
      // console.log('修改密码', res)
      // eslint-disable-next-line
      if (res.code === 0) {

      }
    })
  },

  /**
   * 重置密码
   * @param {String} phone 手机号
   * @param {String} code 随机编码
   * @param {String} captcha 验证码
   * @param {String} pwd 新密码（经过Md5处理过的
   */
  resetPwd(phone, code, captcha, pwd) {
    const params = {
      phone: phone,
      code: code,
      captcha: captcha,
      pwd: md5(pwd)
    }
    const url = constant.ctx + 'auth/api/v2/app/user/restpwd'
    request.putForm(url, params).then((res) => {
      // console.log('重置密码', res)
      // eslint-disable-next-line
      if (res.code === 0) {

      }
    })
  },
  /**
   * 登陆用户登出系统
   */
  outFn() {
    const url = constant.ctx + 'auth/api/v2/app/login/out'
    request.get(url, {}).then((res) => {
      // console.log('登陆用户登出系统', res)
      // eslint-disable-next-line
      if (res.code === 0) {

      }
    })
  },

  /**
   * 解绑/绑定微信openId
   * @param {String} openId 微信openId
   * @param {String} unitId 用户所在当前单位id
   * @param {String} type 1：绑定 2：解绑
   */
  bindWechat(unitId, type) {
    return new Promise((resolve, reject) => {
      const firstUrlParam = common.getKeyVal('user', 'firstUrlParam', 'sessionStorage')
      const params = {
        openId: firstUrlParam.openId,
        unitId: unitId,
        type: type
      }
      const url = constant.ctx + 'auth/api/v2/app/user/bindingopenid'
      request.get(url, params).then((res) => {
        // console.log('绑定微信openId', res)
        if (res.code === 0) {
          resolve(res)
        }
      }).catch(e => {
        reject(e)
      })
    })
  },

  /**
   * 获取 微信信息
   */
  getWechatInfo() {
    return new Promise((resolve, reject) => {
      // debugger
      const firstUrlParam = common.getKeyVal('user', 'firstUrlParam', 'sessionStorage') || {}
      let weChatInfo = {
        nickName: '',
        headImgUrl: '',
        nickNameTip: '', // 解绑/绑定 弹窗使用
        headImgUrlTip: '', // 解绑/绑定 弹窗使用
        isBind: false,
        isShow: false
      }
      // 若没有openId 则设置为获取失败
      if (!firstUrlParam.openId) {
        common.setKeyVal('user', 'weChatInfo', weChatInfo)
        reject()
        return
      }

      const params = {
        openId: firstUrlParam.openId
      }
      const url = constant.ctx + 'wechat/api/v1/openwechatuser/query/one'
      request.get(url, params).then((res) => {
        // console.log('获取微信信息', res)
        // debugger
        if (res.code === 0) {
          if (!validate.isNull(res.result)) {
            weChatInfo = res.result
          }
          // eslint-disable-next-line
          resolve(weChatInfo)
        }
      }).catch(e => {
        reject(e)
      })
    })
  },
  /**
   * 获取 平台未读信息
   */
  getUnreadPlateNum() {
    return new Promise((resolve, reject) => {
      request.get(constant.ctx + 'basics/api/v1/lzdplatformmessageitem/query/unread', {}).then((res) => {
        if (res.code === 0) {
          resolve(res)
        }
      }).catch(error => {
        reject(error)
      })
    })
  },
  /**
   * 获取 园所未读信息
   */
  getUnreadGardentNum() {
    const params = {
      userId: store.state.user.curSelectRole.identityType === '1538' ? store.state.user.curSelectRole.data.studentId : store.state.user.userInfo.id,
      userType: store.state.user.curSelectRole.identityType
    }
    return new Promise((resolve, reject) => {
      request.get(constant.ctx + 'manage/api/v1/lzddynamic/query/unread', params).then((res) => {
        if (res.code === 0) {
          const str = 'grandNum:' + res.result
          resolve(str)
        }
      })
    })
  },
  /**
   * 获取 其他未读信息
   */
  getOhtersUnreadNum() {
    const grandNum = this.getUnreadGardentNum()
    return new Promise((resolve, reject) => {
      return Promise.all([grandNum]).then((res) => {
        resolve(res)
      }).catch(error => {
        reject(error)
        // console.log(error)
      })
    })
  },
  getCodeUserInfo() {
    return new Promise((resolve, reject) => {
      request.get(constant.ctx + 'auth/api/v1/sysuser/query/one').then((res) => {
        if (res.code === 0) {
          resolve(res.result)
        } else {
          reject()
        }
      }).catch(e => {
        reject(e)
      })
    })
  }
}
